package org.springblade.modules.serial;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.modules.alisls.AliSlsProperties;
import org.springblade.modules.alisls.AliyunSlsService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

@Component
@EnableAsync
public class BusinessHandler {

	private static final Logger logger = LoggerFactory.getLogger(BusinessHandler.class);

	@Async
	public void process(String msg, SocketAddress socketAddress){
		byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
		String s = bytesToHex(bytes);
		logger.info("转换后的文本内容{}",s);
		InetSocketAddress inetSocketAddress = (InetSocketAddress)socketAddress;
		InetAddress address = inetSocketAddress.getAddress();
		String hostAddress = address.getHostAddress();
		ArrayList<AliyunSlsService.LogContent> contents = new ArrayList<>();
		AliyunSlsService.LogContent logContent = new AliyunSlsService.LogContent("content",s);
		contents.add(logContent);
		try {
			SpringUtil.getBean(AliyunSlsService.class).pushLog(hostAddress,hostAddress, contents,SpringUtil.getBean(AliSlsProperties.class).getSerialLogstore());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static String bytesToHex(byte[] bytes) {
		StringBuilder sb = new StringBuilder();
		for (byte b : bytes) {
			sb.append(String.format("%02x", b));
		}
		return sb.toString();
	}
}
